﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ovvio.Web.Core;
using Ovvio.Web.Areas.Admin.Models;
using Ovvio.Data;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Ovvio.Web.Areas.Admin.ModelProviders
{
    public class ProductModelProvider : ModelProvider<int, ProductModel, Product, OvvioDataContext>
    {
        public ProductModelProvider()
            : base(p => p.Id, p => p.Id, "Products", "ItemType|Discount|ProductCategory|ProductRating|Promo")
        { }

        public override bool Save(ProductModel model)
        {
            if (model.PostImage  != null)
            {
                if (model.PostImage.InputStream != null)
                {
                    using (var br = new BinaryReader(model.PostImage.InputStream))
                    {
                        model.Entity.Image = br.ReadBytes((int)model.PostImage.InputStream.Length);
                    }
                }
            }
            return base.Save(model);
        }

        public byte[] GetImage(int id)
        {
            var model = Get(id);
            if (model != null)
                return model.Entity.Image;

            return null;
        }

        public byte[] GetThumbnail(int id)
        {
            var imageBinary = GetImage(id);
            if (imageBinary != null)
            {
                var callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                using (var stream = new MemoryStream(imageBinary))
                {
                    var image = Image.FromStream(stream);
                    var thumbnail = image.GetThumbnailImage(50, 50, callback, IntPtr.Zero);
                    using (var thumbStream = new MemoryStream())
                    {
                        thumbnail.Save(thumbStream, ImageFormat.Png);
                        return thumbStream.ToArray();
                    }
                }
                
            }
            return null;
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

    }
}
